package com.kitty.game.pet.service;

import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.thread.IdGenerator;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.bag.message.RespStore;
import com.kitty.game.bag.model.StoreEquipInfo;
import com.kitty.game.config.*;
import com.kitty.game.confirm.model.ExChangePetConfirm;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.enter.RespUpdateImprovement;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.EquipField;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.model.RoleHunQiField;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.fight.service.CountService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.npc.service.NewNpcService;
import com.kitty.game.pet.FeedType;
import com.kitty.game.pet.PetDataPool;
import com.kitty.game.pet.PetType;
import com.kitty.game.pet.bean.PetObject;
import com.kitty.game.pet.handler.FeedHelper;
import com.kitty.game.pet.handler.FeedPetHandler;
import com.kitty.game.pet.message.*;
import com.kitty.game.pet.message.vo.BookInfo;
import com.kitty.game.pet.message.vo.ExChangePetInfo;
import com.kitty.game.pet.message.vo.PetInfo;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBook;
import com.kitty.game.pet.model.PetBox;
import com.kitty.game.rank.model.monitor.PetAttribMonitor;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.shop.RespPetShop;
import com.kitty.game.shop.ShopDataPool;
import com.kitty.game.skill.message.RespUpdateSkill;
import com.kitty.game.skill.message.vo.SkillInfo;
import com.kitty.game.skill.model.RoleSkill;
import com.kitty.game.skill.service.SkillService;
import com.kitty.game.task.service.taskHandler.PetFlyTaskHandler;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.AttrConst;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.FormulaUtil;
import com.kitty.game.utils.NotifyModules;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.annotation.EventHandler;
import com.kitty.listener.event.LoginEvent;
import com.kitty.listener.event.LogoutEvent;
import com.kitty.listener.event.RemovePetEvent;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.MessagePusher;
import com.kitty.common.utils.StaticParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Dao;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PetService {
    Logger logger = LoggerFactory.getLogger(PetService.class);
    @Autowired
    Dao dao;
    @Autowired
    SkillService skillService;
    @Autowired
    CountService countService;
    @Autowired
    BroadcastService broadcastService;
    @Autowired
    RoleService roleService;
    @Autowired
    EquipService equipService;
    @Autowired
    BookService bookService;
    @Autowired
    PetPeiYuanService petPeiYuanService;
    @Autowired
    PetNingShenService petNingShengService;
    @Autowired
    RedisService redisService;
    /**
     * 登出
     */
    @EventHandler(EventType.LOGOUT)
    public void handleLogoutEvent(LogoutEvent logoutEvent) {
        Role role = logoutEvent.getRole();
        updateOffOnline(role);
        role.save();
    }


    /**
     * 初始化兑换宠物数据
     */
    public void initExChangePet(List<ExchangePet> list) {
        Map<String, ExchangePet> name2ExChangePet = new HashMap<>(list.size());
        for (ExchangePet exchangePet : list) {
            name2ExChangePet.put(exchangePet.getName(), exchangePet);
        }
        PetDataPool.name2ExChangePet = name2ExChangePet;
    }

    /**
     * 取兑换宠物数据
     */
    public ExchangePet getExChangePet(String name) {
        return PetDataPool.name2ExChangePet.get(name);
    }

    public List<Pet> getPetList(Role role) {
        return role.getPetBox().getAllPets().values().stream().collect(Collectors.toList());
    }
    public List<Pet> getPetList(Role role,int type) {
        List<Pet> list = new ArrayList<>();
        if(type ==2){
            list =  role.getPetBox().getAllPets().values().stream().filter(pet -> pet.getType() != 6 && pet.getType() != 7 && pet.getType() != 8).collect(Collectors.toList());
        }else{
            list =  role.getPetBox().getAllPets().values().stream().filter(pet -> pet.getType() == 6 || pet.getType() == 7 || pet.getType() == 8).collect(Collectors.toList());
        }
        return list;
    }


    @EventHandler(EventType.LOGIN)
    public void handleLoginEvent(LoginEvent loginEvent) {
        Role role = loginEvent.getRole();


        /**判断宠物属性是否溢出*/


        List<Pet> pets = getPetList(role);
        for (Pet pet : pets) {
            // 110级以下的宠物没有飞升属性
            if (pet.getLevel() < 110){
                pet.setFly((byte) 0);
                NutMap feisheng = NutMap.NEW();
                feisheng.setv("life", 0);
                feisheng.setv("mana", 0);
                feisheng.setv("phy", 0);
                feisheng.setv("mag", 0);
                feisheng.setv("speed", 0);
                pet.setFlyEffect(feisheng);
            }

            PetObject petObject = PetDataPool.getPetObject(pet.getName());

            if (petObject != null) {
                Map<String, Integer> map;
                short maxLife, maxMana, maxSpeed, maxMag, maxPhy;
                short minLife, minMana, minSpeed, minMag, minPhy;
                map = petObject.getGrowInfo(false, "mag");
                maxMag = map.get("max").shortValue();
                minMag = map.get("min").shortValue();
                map = petObject.getGrowInfo(false, "mana");
                maxMana = map.get("max").shortValue();
                minMana = map.get("min").shortValue();
                map = petObject.getGrowInfo(false, "life");
                maxLife = map.get("max").shortValue();
                minLife = map.get("min").shortValue();
                map = petObject.getGrowInfo(false, "speed");
                maxSpeed = map.get("max").shortValue();
                minSpeed = map.get("min").shortValue();
                map = petObject.getGrowInfo(false, "phy");
                maxPhy = map.get("max").shortValue();
                minPhy = map.get("min").shortValue();
                if (pet.getMagEffect() > maxMag) {
                    pet.setMagEffect(maxMag);
                } else if (pet.getMagEffect() < minMag) {
                    pet.setMagEffect(minMag);
                }

                if (pet.getPhyEffect() > maxPhy) {
                    pet.setPhyEffect(maxPhy);
                } else if (pet.getPhyEffect() < minPhy) {
                    pet.setPhyEffect(minPhy);
                }

                if (pet.getSpeedEffect() > maxSpeed) {
                    pet.setSpeedEffect(maxSpeed);
                } else if (pet.getSpeedEffect() < minSpeed) {
                    pet.setSpeedEffect(minSpeed);
                }

                if (pet.getLifeEffect() > maxLife) {
                    pet.setLifeEffect(maxLife);
                } else if (pet.getLifeEffect() < minLife) {
                    pet.setLifeEffect(minLife);
                }

                if (pet.getManaEffect() > maxMana) {
                    pet.setManaEffect(maxMana);
                } else if (pet.getManaEffect() < minMana) {
                    pet.setManaEffect(minMana);
                }
            }
        }


        /**加载宠物*/

        if (pets.size() > 0) {
            for (Pet pet : pets) {
                if (!pet.isInStore()) {//交易的和存入仓库的加载
                    loadPet(role, pet);
                }
                if (pet.getCreatetime() == 0){
                    pet.setCreatetime(System.currentTimeMillis());
                    PetObject petObject = PetDataPool.getPetObject(pet.getName());
                    if (petObject != null ){
//                        if (petObject.getName().equals("太极熊") || petObject.getName().equals("墨麒麟")){
//                            logger.error("八阶坐骑补偿积分=={}",role.getRoleId(),role.getName(),pet.getName(),pet.getCreatetime());
//                            Mail mail = SpringUtils.getMailService().createMail("八阶坐骑补偿购买积分", "八阶坐骑补偿购买积分", 30 * TimeUtil.ONE_DAY);
//                            ArrayList<NutMap> maps = new ArrayList<>();//(x5+2*技+2*敏)
//                            maps.add(new NutMap().setv("data", "#I积分|积分#r888#I").setv("type", Const.jifen).setv("petName", "积分").setv("value",888));
//                            mail.getDatas().addAll(maps);
//                            SpringUtils.getMailService().sendNewMail(role,mail);
//                        }
                    }
                }
            }
        }


        // 宠物超过15级的

        for (Pet pet :pets){
            if (pet.getId() == role.getPetBox().getSupplyPetId()){
                if (pet.getLevel() - role.getLevel() > 15){
                    role.getPetBox().setSupplyPetId(0);
                }
            }
            if (pet.getId() == role.getPetBox().getFightPetId()){
                if (pet.getLevel() - role.getLevel() > 15){
                    role.getPetBox().setFightPetId(0);
                }
            }
        }



        // 参战宠物
        if (role.getPetBox().getFightPetId() != 0) {
            RespSetCurrentPet respSetCurrentPet = new RespSetCurrentPet();
            respSetCurrentPet.setPetId(role.getPetBox().getFightYangPetId());
            respSetCurrentPet.setStatus((short) 1);
            MessagePusher.pushMessage(role, respSetCurrentPet);
            respSetCurrentPet.setPetId(role.getPetBox().getFightGhostPetId());
            respSetCurrentPet.setStatus((short) 1);
            MessagePusher.pushMessage(role, respSetCurrentPet);
        }
        // 掠阵宠物
        if (role.getPetBox().getSupplyPetId() != 0) {

            RespSetCurrentPet respSetCurrentPet = new RespSetCurrentPet();
            respSetCurrentPet.setPetId(role.getPetBox().getSupplyYangPetId());
            respSetCurrentPet.setStatus((short) 2);
            MessagePusher.pushMessage(role, respSetCurrentPet);
            respSetCurrentPet.setPetId(role.getPetBox().getSupplyGhostPetId());
            respSetCurrentPet.setStatus((short) 2);
            MessagePusher.pushMessage(role, respSetCurrentPet);
        }

        /**
         * 当前骑乘坐骑
         */


        if (role.getMount() != 0) {
            RespCurrentMount respCurrentMount = new RespCurrentMount();
            respCurrentMount.setMountId(role.getMount());
            MessagePusher.pushMessage(role, respCurrentMount);
        }

        role.save();

    }

    /**
     * 取宠物仓库空位
     *
     * @return
     */
    public short getPetStoreNull(Role role, IoSession session) {
        short min = 351;
        PetStore petStore = role.getPetBox().getPetStore();
        Map<Short, Integer> hashMap = petStore.getPetInfo();
        if (hashMap == null || hashMap.size() == 0) {
            return min;
        } else if (hashMap.size() >= 14) {
            MessagePusher.notify2Player(session, I18nId.PMT_100);
        } else {
            for (short i = min; i <= 365; i++) {
                boolean boo = false;
                for (Map.Entry<Short, Integer> entry : hashMap.entrySet()) {
                    if (i == entry.getKey()) {
                        boo = true;
                        break;
                    }
                }
                if (boo) {
                    continue;
                } else {
                    return i;
                }
            }
        }
        return -1;
    }

    /**
     * 发送宠物仓库
     *
     * @return
     */
    public void sendPetStore(Role role) {
        PetBox petBox = role.getPetBox();
        PetStore petStore = petBox.getPetStore();

        Map<Integer, Pet> petMap = petBox.getAllPets();
        Map<Short, Integer> hashMap = petStore.getPetInfo();
        for (Map.Entry<Short, Integer> entry : hashMap.entrySet()) {
            Pet pet = petMap.get(entry.getValue());
            if (pet != null) {
                sendPetStore(role, entry.getKey(), pet);
            }
        }
    }

    /**
     * 取出宠物发送
     */
    public void sendNullPetStore(IoSession session, short pos) {
        RespStore respStore = new RespStore();
        respStore.setStr("pet_store");
        ArrayList<StoreEquipInfo> arrayList = new ArrayList<>();
        respStore.setList(arrayList);
        StoreEquipInfo storeEquipInfo = new StoreEquipInfo();
        storeEquipInfo.setIndex((byte) 0);
        storeEquipInfo.setPos(pos);
        arrayList.add(storeEquipInfo);
        MessagePusher.pushMessage(session, respStore);
    }

    /**
     * 存入宠物发送
     */
    public void sendPetStore(Role role, short pos, Pet pet) {
        RespStore respStore = new RespStore();
        respStore.setStr("pet_store");
        ArrayList<StoreEquipInfo> arrayList = new ArrayList<>();
        respStore.setList(arrayList);
        StoreEquipInfo storeEquipInfo = new StoreEquipInfo();
        storeEquipInfo.setPos(pos);
        List<EquipField> list = new ArrayList<>();
        List<RoleHunQiField> hunqi = new ArrayList<>();
        list.addAll(pet.getAllFields());
        storeEquipInfo.setEquipFields(list, hunqi);
        arrayList.add(storeEquipInfo);
        MessagePusher.pushMessage(role, respStore);
    }

    public Set<String> getBianyiList() {
        return DataCache.VARIATION;
    }

    /**
     * 增加宠物限制时间
     * 一个物品增加10天
     */
    public void addLimitTime(Pet pet, int limitNum) {
        int value = pet.getLimitTime();
        int currTime = new Long(System.currentTimeMillis() / 1000).intValue();
        if (value == 0) {
            value = currTime;
            pet.setLimitTime(-(value + 864000 * limitNum));// 增加限制天数
        } else {
            if (-value + 864000 * limitNum >= currTime + 864000 * 6) {
                pet.setLimitTime(-(currTime + 864000 * 6));// 增加限制天数
            } else {
                pet.setLimitTime(value - 864000 * limitNum);// 增加限制天数
            }
        }
    }

    /**
     * 增加宠物限制时间
     * 一个物品增加10天
     */
    public void addLimitTimeDay(Pet pet, int limitNum) {
        int value = pet.getLimitTime();
        int currTime = new Long(System.currentTimeMillis() / 1000).intValue();
        if (value == 0) {
            value = currTime;
            pet.setLimitTime(-(value + 86400 * limitNum));// 增加限制天数
        } else {
            if (-value + 86400 * limitNum >= currTime + 864000 * 6) {
                pet.setLimitTime(-(currTime + 864000 * 6));// 增加限制天数
            } else {
                pet.setLimitTime(value - 86400 * limitNum);// 增加限制天数
            }
        }
    }

    /**
     * 宠物位置取宠物
     */
    public Pet getPetByPos(byte pos, Role role) {
        return role.getPetBox().getEquippedPetByPosition(pos);
    }
    public List<Pet> getPetByName(String name, Role role) {
        return role.getPetBox().getEquippedPetByPetName(name,role);
    }
    public PetSet getPetSet(int icon) {
        return DataCache.ICON_PETSET.get((short) icon);
    }

    public PetSet getPetByName(String name) {
        short icon = DataCache.NAME_ICON.get(name);
        PetSet petSet = getPetSet(icon);
        if (petSet == null) {
            icon = (short) (icon - 1000);
            return getPetSet(icon);
        }
        return petSet;
    }

    private void add(Role role, Pet pet) {
        int petId = SpringUtils.getIdentityService().getNextId(IdentityType.ROLE);
        pet.setId(petId);
//        pet.setRepairedId(true);
        if (pet.getMagEffect() > pet.getPhyEffect()) {
            Map<String, Byte> nutMap = new HashMap<>();
            nutMap.put("con", (byte) 0);
            nutMap.put("str",  (byte)0);
            nutMap.put("dex",  (byte)1);
            nutMap.put("wiz",  (byte)3);
            nutMap.put("status",  (byte)1);
            nutMap.put("type",  (byte)1);
            pet.setAutoAtrrib(nutMap);
        } else {
            Map<String, Byte> nutMap = new HashMap<>();
            nutMap.put("con", (byte) 0);
            nutMap.put("str", (byte) 3);
            nutMap.put("dex", (byte) 1);
            nutMap.put("wiz", (byte) 0);
            nutMap.put("status", (byte) 1);
            nutMap.put("type", (byte) 1);
            pet.setAutoAtrrib(nutMap);
        }
        NutMap dianhua = NutMap.NEW();
        dianhua.setv("life", 0);
        dianhua.setv("mana", 0);
        dianhua.setv("phy", 0);
        dianhua.setv("mag", 0);
        dianhua.setv("speed", 0);
        NutMap yuhua = NutMap.NEW();
        yuhua.setv("life", 0);
        yuhua.setv("mana", 0);
        yuhua.setv("phy", 0);
        yuhua.setv("mag", 0);
        yuhua.setv("speed", 0);
        NutMap refineMap = NutMap.NEW();
        refineMap.setv("life", 0);
        refineMap.setv("mana", 0);
        refineMap.setv("phy", 0);
        refineMap.setv("mag", 0);
        refineMap.setv("speed", 0);
        NutMap feisheng = NutMap.NEW();
        feisheng.setv("life", 0);
        feisheng.setv("mana", 0);
        feisheng.setv("phy", 0);
        feisheng.setv("mag", 0);
        feisheng.setv("speed", 0);

        pet.setRefineMap(refineMap);
        pet.setEnchantEffect(dianhua);
        pet.setEclosionEffect(yuhua);
        pet.setFlyEffect(feisheng);
        pet.setGid(String.valueOf(IdGenerator.getNextId()));

        role.getPetBox().addNewPet(pet);

    }

    public byte getNewPetPos(Role role, Pet pet) {
        PetBox petBox = role.getPetBox();
        byte result = 1;

        while(true) {
            Pet tmpPet = petBox.getEquippedPetByPosition(result,true);
            if (tmpPet == null || tmpPet.getId() == pet.getId()) {
                return result;
            }

            ++result;
        }
    }

    public Pet getPetById(int petId, Role role) {
        PetBox petBox = role.getPetBox();
        return petBox.getPetByPetId(petId);
    }

    /**
     * 添加宠物
     */
    public Pet addPet(PetObject petObject, Role role, boolean limit) {
        Pet pet = new Pet();
        if (limit) {
            pet.setLimitTime(2);
        }
        byte petTypeByName = StaticParam.getPetTypeByName(petObject.getName());
        if( petTypeByName == 8){//这里可能是 抓坐骑最高介位
            roleService.addAchieveScore(role,"201042");
        }
        setPetEffect(petObject, pet);
        add(role, pet);
        pet.setExp(0);
        pet.setReqLevel(petObject.getLevel_req());
        pet.setIntimacy(0);
        pet.setHostId(role.getRoleId());
        pet.setHostName(role.getName());
        pet.setMartial(Const.INIT_PET_WUXUE);
        pet.setName(petObject.getName());
        pet.setNickname(petObject.getName());
        pet.setItype((byte) (petObject.getCapacity_level() > 0 ? 1 : 0));
        pet.setIcon(petObject.getIcon());
        pet.setLevel((short) 1);
        pet.setType((byte) (petObject.getPetType() > 4 ? 2 : petObject.getPetType()));
        pet.setCreatetime(System.currentTimeMillis());
        if (petObject.getPetType() == PetType.ghost){
            pet.setType(StaticParam.getPetTypeByName(petObject.getName()));
        }
        pet.setPolar(petObject.getPolar());
        Random random = new Random();
        pet.setLongevity(random.nextInt(5000) + 10000);
        pet.setBasicAttrib();
        pet.setLastAtrrib(roleService.getLastAttributePoint(pet));
        pet.setLastResistPoint(roleService.getLastPolarPoint(pet));
        pet.setCurrLife(countService.countPetMaxLife(pet));
        pet.setCurrMana(countService.countPetMaxMana(pet));
        if (pet.getItype() >= 1) {
            pet.setRankItem((short) (petObject.getIcon() + 1000));
            pet.setRank(petObject.getCapacity_level());
            if(petObject.getCapacity_level()>=2){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201009");
            }
            if(petObject.getCapacity_level()>=3){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201056");
            }
            if(petObject.getCapacity_level()>=4){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201002");
            }
            if(petObject.getCapacity_level()>=5){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201007");
            }
            if(petObject.getCapacity_level()>=6){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201022");
            }
            if(petObject.getCapacity_level()>=8){
                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201052");
            }
//            if(petObject.getCapacity_level()>=9){
//                SpringUtils.getBean(RoleService.class).addAchieveScore(role,"201054");
//            }
        }
        role.save();
        return pet;
    }

    /**
     * 设置宠物成长
     */
    public void setPetEffect(PetObject petObject, Pet pet) {
        int phy = getRandomValue(petObject.getGrowInfo(false, "phy"));
        int mag = getRandomValue(petObject.getGrowInfo(false, "mag"));
        int life = getRandomValue(petObject.getGrowInfo(false, "life"));
        int mana = getRandomValue(petObject.getGrowInfo(false, "mana"));
        int speed = getRandomValue(petObject.getGrowInfo(false, "speed"));

        pet.setPhyEffect((short) phy);
        pet.setMagEffect((short) mag);
        pet.setLifeEffect((short) life);
        pet.setManaEffect((short) mana);
        pet.setSpeedEffect((short) speed);
    }

    /**
     * 购买野生宠物
     *
     * @param petObject
     * @return
     */
    public Pet addWildPet(PetObject petObject, Role role) {
        Pet pet = new Pet();
        add(role, pet);
        setPetEffect(petObject, pet);
        pet.setExp(0);
        pet.setReqLevel(petObject.getLevel_req());
        pet.setIntimacy(0);
        pet.setHostId(role.getRoleId());
        pet.setHostName(role.getName());
        pet.setName(petObject.getName());
        pet.setNickname(petObject.getName());
        pet.setIcon(petObject.getIcon());
        pet.setCreatetime(System.currentTimeMillis());
        short level = petObject.getLevel_req();
        if (level > 120) {
            level = 120;
        }
        pet.setPosition(getNewPetPos(role, pet));
        pet.setLevel(level);
        pet.setType((byte) 1);
        pet.setPolar((byte) petObject.getPolar());
        pet.setItype((byte) (petObject.getCapacity_level() > 2 ? 1 : 0));
        Random random = new Random();
        pet.setBasicAttrib();
        pet.setLastAtrrib(roleService.getLastAttributePoint(pet));
        pet.setLastResistPoint(roleService.getLastPolarPoint(pet));
        /**野生宠物 直接把属性点分配完*/
        while (pet.getLastAtrrib() >= 1) {
            int nextInt = random.nextInt(100);
            if (nextInt >= 75) {
                pet.setStr((short) (pet.getStr() + 1));
            } else if (nextInt >= 50) {
                pet.setWiz((short) (pet.getWiz() + 1));
            } else if (nextInt >= 25) {
                pet.setDex((short) (pet.getDex() + 1));
            } else {
                pet.setCon((short) (pet.getCon() + 1));
            }
            pet.setLastAtrrib(roleService.getLastAttributePoint(pet));
        }
        /**野生宠物 直接把抗性点分配完*/
        while (pet.getLastResistPoint() >= 1) {
            int nextInt = random.nextInt(100);
            if (nextInt >= 90) {
                pet.setResistConfusion(pet.getResistConfusion() + 1);
            } else if (nextInt >= 80) {
                pet.setResistEarth(pet.getResistEarth() + 1);
            } else if (nextInt >= 70) {
                pet.setResistFire(pet.getResistFire() + 1);
            } else if (nextInt >= 60) {
                pet.setResistForgotten(pet.getResistForgotten() + 1);
            } else if (nextInt >= 50) {
                pet.setResistFrozen(pet.getResistFrozen() + 1);
            } else if (nextInt >= 40) {
                pet.setResistMetal(pet.getResistMetal() + 1);
            } else if (nextInt >= 30) {
                pet.setResistPoison(pet.getResistPoison() + 1);
            } else if (nextInt >= 20) {
                pet.setResistSleep(pet.getResistSleep() + 1);
            } else if (nextInt >= 10) {
                pet.setResistWater(pet.getResistWater() + 1);
            } else {
                pet.setResistWood(pet.getResistWood() + 1);
            }
            pet.setLastResistPoint(roleService.getLastPolarPoint(pet));
        }

        if (pet.getLevel() >= 20) {
            roleService.setPetSkill(role, pet);
        }
        pet.setLongevity(random.nextInt(5000) + 10000);
        pet.setCurrLife(countService.countPetMaxLife(pet));
        pet.setCurrMana(countService.countPetMaxMana(pet));
        role.save();
        return pet;
    }

    /**
     * 宠物成长取随机值
     */
    public int getRandomValue(Map<String, Integer> map) {
        if (map.size() < 2) {
            return 0;
        }
        int min = map.get("min");
        int max = map.get("max");
        Random random = new Random();
        if (max == min) {
            return max;
        }
        return random.nextInt(max - min) + min + 1;
    }

    /**
     * 取成长最大值
     */
    public int getMaxValue(Map<String, Integer> map) {
        if (map.size() < 2) {
            return 0;
        }
        return map.get("max");
    }

    /**
     * 取成长最小值
     */
    public int getMinValue(Map<String, Integer> map) {
        if (map.size() < 2) {
            return 0;
        }
        return map.get("min");
    }


    /**
     * 取坐骑坐姿
     */
    public int getMountPosture(Role role, Pet pet) {
        int zishi = 0;
        if (pet.getName().contains("芦")) {
            if (role.getPolar() == 1) {
                if (role.getGender() == 1) {
                    zishi = 760021;
                } else {
                    zishi = 770021;
                }
            } else if (role.getPolar() == 2) {
                if (role.getGender() == 1) {
                    zishi = 770022;
                } else {
                    zishi = 760022;
                }
            } else if (role.getPolar() == 3) {
                if (role.getGender() == 1) {
                    zishi = 770023;
                } else {
                    zishi = 760023;
                }
            } else if (role.getPolar() == 4) {
                if (role.getGender() == 1) {
                    zishi = 760024;
                } else {
                    zishi = 770024;
                }
            } else if (role.getPolar() == 5) {
                if (role.getGender() == 1) {
                    zishi = 760025;
                } else {
                    zishi = 770025;
                }
            } // 元婴和血婴类型
            if (role.getChildInfo().getState() == 1)
                zishi = 760020;
            else if (role.getChildInfo().getState() == 2)
                zishi = 770020;
      } else if (pet.getName().contains("剑") || pet.getName().contains("斗云")) {
            if (role.getPolar() == 1) {
                if (role.getGender() == 1) {
                    zishi = 760011;
                } else {
                    zishi = 770011;
                }
            } else if (role.getPolar() == 2) {
                if (role.getGender() == 1) {
                    zishi = 770012;
                } else {
                    zishi = 760012;
                }
            } else if (role.getPolar() == 3) {
                if (role.getGender() == 1) {
                    zishi = 770013;
                } else {
                    zishi = 760013;
                }
            } else if (role.getPolar() == 4) {
                if (role.getGender() == 1) {
                    zishi = 760014;
                } else {
                    zishi = 770014;
                }
            } else if (role.getPolar() == 5) {
                if (role.getGender() == 1) {
                    zishi = 760015;
                } else {
                    zishi = 770015;
                }
            }
        } else {//熊 鹿 豹
            if (role.getPolar() == 1) {
                if (role.getGender() == 1) {
                    zishi = 760031;
                } else {
                    zishi = 770021;
                }
            } else if (role.getPolar() == 2) {
                if (role.getGender() == 1) {
                    zishi = 770032;
                } else {
                    zishi = 760022;
                }
            } else if (role.getPolar() == 3) {
                if (role.getGender() == 1) {
                    zishi = 770033;
                } else {
                    zishi = 760023;
                }
            } else if (role.getPolar() == 4) {
                if (role.getGender() == 1) {
                    zishi = 760034;
                } else {
                    zishi = 770024;
                }
            } else if (role.getPolar() == 5) {
                if (role.getGender() == 1) {
                    zishi = 760035;
                } else {
                    zishi = 770025;
                }
            }
        }
        return zishi;
    }


    /**
     * 刷新宠物面板
     */

    public void refreshPetInfo(Role role, Pet pet) {

        sendPetInfoPacket(role, pet);
    }

    /**
     * 刷新宠物面板
     */

    public void refreshPetPeiYuanInfo(Role role, Pet pet) {
        sendPetInfoPacket(role, pet);
    }

    /**
     * 加载宠物
     */
    public void loadPet(Role role, Pet pet) {
        pet.setPosition(getNewPetPos(role, pet));
        pet.setGid(pet.getId() + "");

        sendPetInfoPacket(role, pet);

        List<RoleSkill> tempList = pet.getSkillBox().queryAllSkills();
        RespUpdateSkill respUpdateSkill = new RespUpdateSkill();
        respUpdateSkill.setId(pet.getId());
        ArrayList<SkillInfo> skillInfos = new ArrayList<>();
        for (RoleSkill roleSkill : tempList) {
            if (roleSkill.getLevel() <= 0){
                continue;
            }
            skillInfos.add(skillService.getSkillInfo(roleSkill, 0));
        }
        respUpdateSkill.setList(skillInfos);
        MessagePusher.pushMessage(role, respUpdateSkill);

        /**
         * 声明主人  消失宠物 hostId置0
         */
        RespPetHost respPetHost = new RespPetHost();
        respPetHost.setPetId(pet.getId());
        respPetHost.setHostId(role.getRoleId());
        MessagePusher.pushMessage(role, respPetHost);

        /**
         * 面板
         */
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(pet.getId());
        respUpdate.setList(new ArrayList<>());
        MessagePusher.pushMessage(role, respUpdate);
        if (pet.getType() == 6 || pet.getType() == 7 || pet.getType() == 8){
            petPeiYuanService.sendPeiYuanPanel(role, pet,false);
            petNingShengService.getNingShenPanel(role, pet);
        }
        /**
         * 加载宠物天书
         */
        ArrayList<BookInfo> bookList = new ArrayList<>();
        Map<Integer, PetBook> bookHashMap = role.getPetBox().getPetBooks(pet.getId());
        for (Map.Entry<Integer, PetBook> entry : bookHashMap.entrySet()) {
            PetBook petBook = entry.getValue();
            if (petBook != null) {
                BookInfo bookInfo = new BookInfo();
                bookInfo.setBookLevel(petBook.getBookLevel());
                bookInfo.setBookName(petBook.getBookName());
                bookInfo.setEnable(petBook.isEnable());
                bookInfo.setLingqi(petBook.getLingqi());
                bookList.add(bookInfo);
            }
        }
        RespPetBook respPetBook = new RespPetBook();
        respPetBook.setRoleId(role.getRoleId());
        respPetBook.setPetId(pet.getId());
        respPetBook.setList(bookList);
        MessagePusher.pushMessage(role, respPetBook);

    }

    private void sendPetInfoPacket(Role role, Pet pet) {
        RespPetInfo respPetInfo = new RespPetInfo();
        List<PetInfo> petInfos = new ArrayList();
        PetInfo petInfo = new PetInfo();
        petInfos.add(petInfo);
        petInfo.setPosition(pet.getPosition());
        petInfo.setPetId(pet.getId());
        List<EquipField> petFields = new ArrayList(pet.getAllFields());
        petInfo.setList(petFields);
        respPetInfo.setPetInfos(petInfos);
        MessagePusher.pushMessage(role, respPetInfo);
        ArrayList<FiedValue> values = new ArrayList();
        pet.getStones().forEach((petStone) -> {
            values.add(new FiedValue(1, petStone.getName()));
            values.add(new FiedValue(petStone.getFieldId(), petStone.getValue()));
            values.add(new FiedValue(118, petStone.getNimbus()));
        });
        RespUpdateImprovement improvement = new RespUpdateImprovement();
        improvement.setId(pet.getId());
        improvement.setList(values);
        MessagePusher.pushMessage(role, improvement);
    }


    /**
     * 取坐骑增加属性
     */

    public EquipField getMountAttrib(Pet pet) {
        short icon = pet.getIcon();
        if (pet.getItype() > 0) {
            icon = pet.getRankItem();
        }
        PetSet petSet = getPetSet(icon);
        NutMap mountMap = petSet.getMountFields();
        int speed = (short) mountMap.getInt("max_speed", 0);
        short attrib = (short) mountMap.getInt("all_attrib", 0);
        int phy = mountMap.getInt("power", 0);
        int mag = (int) (phy * 0.75);
        int def = mountMap.getInt("def", 0);
        int point = mountMap.getInt("upgrade_point", 0);
        short attAll = (short) Math.ceil(pet.getLevel() / attrib);
        /////////
//        if (petSet.getName().equals("太极熊") || petSet.getName().equals("墨麒麟")) {
//            Role role = SpringUtils.getPlayerService().getPlayerBy(SpringUtils.getPlayerService().getUidBy(pet.getHostId()));
////            if (pet.getRank() >=8 ){
////                HunPoProp hunPoProp = SpringUtils.getBean(HunPoService.class).getHunPoProp(role);
////                if (hunPoProp.getLevel() * 10 + hunPoProp.getLevelInner() >= 110) {
////                    attAll = 35;
////                }else if (role.getTotalCharge() >= 10000){
////                    attAll = 23;
////                }else if (role.getTotalCharge() >= 5000){
////                    attAll = 20;
////                }else {
////                    attAll = 15;
////                }
////            }
//            if (pet.getRank() >=8 ){
////                HunPoProp hunPoProp = SpringUtils.getBean(HunPoService.class).getHunPoProp(role);
//                if (role.getPetBox().getZuoqi().contains(18)) {
//                    attAll = 100;
//                }else if (role.getPetBox().getZuoqi().contains(15)) {
//                    attAll = 70;
//                }else if (role.getPetBox().getZuoqi().contains(13)){
//                    attAll = 46;
//                }else if (role.getPetBox().getZuoqi().contains(10)){
//                    attAll = 40;
//                }else{
//                    attAll = 20;
//                }
//            }
//            phy = (phy * 2);
//            mag = (mag * 2);
//            def = (def * 2);
//            point = (point / 2);
//        }
        ///////////////
        ArrayList<FiedValue> arrayList = new ArrayList<>();
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType(AttrConst.fashang);
            fiedValue.setVT((byte) 3);
            fiedValue.setValue(mag * pet.getLevel());
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType(AttrConst.wushang);
            fiedValue.setVT((byte) 3);
            fiedValue.setValue(phy * pet.getLevel());
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType(AttrConst.fangyu);
            fiedValue.setVT((byte) 3);
            fiedValue.setValue(def * pet.getLevel());
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 925);
            fiedValue.setVT((byte) 3);
            fiedValue.setValue((short) Math.ceil(pet.getLevel() / point));
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 926);
            fiedValue.setVT((byte) 3);
            fiedValue.setValue((short) Math.ceil(pet.getLevel() / point));
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType(AttrConst.suoyouShuxin);
            fiedValue.setVT((byte) 2);
            fiedValue.setValue(attAll);
            arrayList.add(fiedValue);
        }
        {
            FiedValue fiedValue = new FiedValue();
            fiedValue.setType((short) 448);
            fiedValue.setVT((byte) 1);
            fiedValue.setValue(pet.getZhuru());
            arrayList.add(fiedValue);
        }
        EquipField equipField = new EquipField();
        equipField.setType((short) 5890);
        equipField.setFieldValues(arrayList);
        return equipField;
    }

    /**
     * 坐骑隐藏
     *
     * @param session
     * @param reqHideMount
     */
    public void hideMount(IoSession session, ReqHideMount reqHideMount) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) return;
        if (role.getMount() == reqHideMount.getMountId()) {
            role.setHideMount(reqHideMount.isHide());
            broadcastService.sendUpdateAppear(role);

            List<FiedValue> list = new ArrayList<>();
            {
                FiedValue fiedValue = new FiedValue();
                fiedValue.setType((short) 886);       //隐藏坐骑
                fiedValue.setVT((byte) 1);
                fiedValue.setValue(role.isHideMount() ? (byte) 1 : (byte) 0);
                list.add(fiedValue);
            }
            RespUpdate respUpdate = new RespUpdate();
            respUpdate.setList(list);
            respUpdate.setRoleId(reqHideMount.getMountId());
            MessagePusher.pushMessage(session, respUpdate);
            role.save();
        }
    }

    /**
     * 是否可以删除宠物
     * @param role
     * @param pet
     */
    public void isDelPet(Role role, Pet pet) {
        //判断共生
        if(pet != null){
            if(StringUtils.isNotEmpty(pet.getGongSheng_pet_id())){
                MessagePusher.pushMessage(role,new RespNotifyMiscEx("共生宠物无法删除"));
                throw new IllegalArgumentException("共生宠物无法删除。");
            }
        }
    }
    /**
     * 丢弃宠物
     *
     * @param role
     * @param pet
     */
    public void delPet(Role role, Pet pet) {
        isDelPet( role,  pet);
        log.error("删除宠物=={}=={}=={}=={}",role.getRoleId(),role.getName(),pet.getName(),pet.getId());
        role.getPetBox().removePet(pet);
        /** 产生一个移除宠物事件 */
        EventDispatcher.getInstance().fireEvent(new RemovePetEvent(EventType.REMOVE_PET, role, pet));
        RespPetHost respPetHost = new RespPetHost();
        respPetHost.setPetId(pet.getId());
        MessagePusher.pushMessage(role, respPetHost);
    }

    public void exChangePet(Role role, String msg) {
        byte type = 0;
        switch (msg) {
            case "我要兑换变异宠物": {
                type = 1;
                break;
            }
            case "我要兑换神兽宠物": {
                type = 2;
                break;
            }
            case "神兽召唤之术": {
                type = 3;
                break;
            }
            case "超级神兽丹": {
                type = 4;
                break;
            }
        }
        if (type == 0) {
            return;
        }
        if (type == 4){
            IoSession session = SessionUtils.getSessionBy(role.getUid());
//            byte petPos = reqFeedPet.getNo();
            RoleEquip roleEquip = equipService.getRoleEquipByName(session, "超级神兽丹");
            if (roleEquip == null) {
                MessagePusher.pushMessage(role,new RespNotifyMiscEx("超级神兽丹不足"));
                return;
            }
            PetService petService = SpringUtils.getPetService();
            Pet pet = petService.getPetById(role.getPetBox().getFightPetId(), role);
            if (pet == null) {
                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有参战宠物"));
                return;
            }
            PetAttribMonitor petAttribMonitor = new PetAttribMonitor(role, pet);
            FeedPetHandler handler = FeedHelper.INSTANCE.getHandler(FeedType.USE_DAN.getType());
            if (handler != null) {
                String tips = handler.acceptFeed(pet, role, roleEquip);
                if (!Strings.isEmpty(tips)) {
                    MessagePusher.pushMessage(session, new RespNotifyMiscEx(tips));
                }
                petService.refreshPetInfo(role, pet);
                role.save();
            } else {
                MessagePusher.pushMessage(session, new RespMsg("很抱歉，该功能暂未开放。"));
            }
            RespPreviewSpecialSkill respPreviewSpecialSkill = new RespPreviewSpecialSkill();
            MessagePusher.pushMessage(session, respPreviewSpecialSkill);

            role.save();
            petAttribMonitor.end();
            return;
        }
        if (type == 3) {//神兽召唤之术
            sendPetStore(role);
            RespExchangeEpicPetShop respExchangeEpicPetShop = new RespExchangeEpicPetShop();
            ArrayList<String> names = new ArrayList<>();
            names.add("疆良");
            names.add("东山神灵");
            names.add("玄武");
            names.add("朱雀");
            names.add("九尾狐");
            names.add("白矖");
            respExchangeEpicPetShop.setList(names);
            MessagePusher.pushMessage(role, respExchangeEpicPetShop);
        } else {//令牌兑换变异或者神兽
            List<ExChangePetInfo> list = new ArrayList<>();
            for (Map.Entry<String, ExchangePet> entry : PetDataPool.name2ExChangePet.entrySet()) {
                ExchangePet exchangePet = entry.getValue();
                if (exchangePet.getType() == type) {
                    ExChangePetInfo exChangePetInfo = new ExChangePetInfo();
                    exChangePetInfo.setName(exchangePet.getName());
                    exChangePetInfo.setPrice(exchangePet.getNum());
                    list.add(exChangePetInfo);
                }
            }
            RespExchangePet respExchangePet = new RespExchangePet();
            respExchangePet.setType(type);
            respExchangePet.setList(list);
            MessagePusher.pushMessage(role, respExchangePet);

        }

    }

    /**
     * 确定兑换宠物
     */
    public void exChangePet(Role role) {
        ExChangePetConfirm confirm = (ExChangePetConfirm) role.getConfirm();
        String petName = confirm.getExchangePet().getName();
        int type = confirm.getExchangePet().getType();
        PetObject petObject = PetDataPool.getPetObject(petName);
        if (petObject == null) {
            return;
        }
        if (SpringUtils.getPetService().isEquippedFull(role)) {
            MessagePusher.pushMessage(role,new RespMsg("当前宠物包裹已满，请整理后再来吧。"));
            return;
        }
        if (type == 1) {
            int count = equipService.getCount("召唤令·十二生肖", true, role);
            if (count < 100) {
                return;
            } else {
                logger.warn("兑换变异=={}=={}", role.getName(), petName);
                equipService.delRoloEquip("召唤令·十二生肖", 100, true, role);
                roleService.addAchieveScore(role,"201035");
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你使用了#R100#n个#R召唤令·十二生肖#n，兑换了一只#Y" + petObject.getName() + "（变异）#n。"));
            }
        } else if (type == 2) {
            int count = equipService.getCount("召唤令·上古神兽", true, role);
            if (count < 100) {
                return;
            } else {
                logger.warn("兑换神兽=={}=={}", role.getName(), petName);
                equipService.delRoloEquip("召唤令·上古神兽", 100, true, role);
                roleService.addAchieveScore(role,"201050");
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("你使用了#R100#n个#R召唤令·上古神兽#n，兑换了一只#Y" + petObject.getName() + "（神兽）#n。"));
                SpringUtils.getChatService().sendAdnotice("玩家#R"+role.getName()+"#n使用了#R100#n个#R召唤令·上古神兽#n，兑换了一只#Y" + petObject.getName() + "（神兽）#n。");
            }
        }
        Pet pet = addPet(petObject, role, false);
        loadPet(role, pet);
        RespIconCartoon respIconCartoon = new RespIconCartoon();
        respIconCartoon.setType((short) 2);
        respIconCartoon.setName(petName);
        respIconCartoon.setParam(petObject.getIcon() + "");
        MessagePusher.pushMessage(role, respIconCartoon);

        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTICE_BUY_ELITE_PET);
        respGeneralNotify.setValue(petObject.getName());
        MessagePusher.pushMessage(role, respGeneralNotify);
    }

    public void updateOffOnline(Role role) {
        Set<Integer> set = role.getPetBox().allPets();
        Set<Integer> idSet = new HashSet<>(set);
        for (Integer petId : idSet) {
            Pet pet = getPetById(petId, role);
            if (pet != null) {
                pet.setPhyPower(countService.countPetMaxPhyPower(pet));
                pet.setMagPower(countService.countPetMaxMagPower(pet));
                pet.setDefense(countService.countPetMaxDefense(pet));
                pet.setSpeed(countService.countPetMaxSpeed(pet));
            }
        }
        role.save();
    }

    /**
     * 使用天生技能秘笈
     *
     * @param pet
     * @param roleEquip
     */
    public void useSkillBook(Role role, Pet pet, RoleEquip roleEquip) {
        int skillId = 0;
        if (roleEquip.getName().contains("神龙罩秘笈")) {
            skillId = 260;
        } else if (roleEquip.getName().contains("如意圈秘笈")) {
            skillId = 254;
        } else if (roleEquip.getName().contains("乾坤罩秘笈")) {
            skillId = 259;
        }else if (roleEquip.getName().contains("舍命一击秘笈")) {
            skillId = 258;
        }else if (roleEquip.getName().contains("十万火急秘笈")) {
            skillId = 181;
        }
        if (skillId == 0) {
            MessagePusher.pushMessage(role, new RespMsg("该秘笈暂时无法使用。"));
            return;
        }
        Skill skill = skillService.getSkillInfo(skillId);
        if (skill == null) {
            return;//没有技能信息
        }

        /**判断宠物是否可以学习这个天生技能*/
        PetObject petObject = PetDataPool.getPetObject(pet.getName());
        if (!petObject.getSkills().contains(skill.getSkillName())) {
            MessagePusher.notify2Player(role, I18nId.PMT_410, skill.getSkillName());
            return ;
        }

        RoleSkill petSkill = skillService.getPetSkill(skillId, pet);
        if (petSkill == null) {
            equipService.delEquipNum(role, roleEquip, 1);
            RoleSkill roleSkill = new RoleSkill();
            roleSkill.setName(skill.getSkillName());
            roleSkill.setRoleId(pet.getId());
            roleSkill.setType((short) skill.getSkillType());
            roleSkill.setSkillId(skillId);
            roleSkill.setSkillJieshu(skill.getJeishu());
            roleSkill.setLevel((short) 1);
            roleSkill.setMana(30);
            roleSkill.setTargetCount((short) skill.getMaxTarget());
            skillService.petLearn(roleSkill, role, pet);
            loadPet(role, pet);
        } else {
            MessagePusher.pushMessage(role, new RespMsg("你的#R" + pet.getNickname() + "#n已经学习过了该秘笈。"));
        }
    }

    /**
     * 添加宠物
     *
     * @param role
     * @param petName
     * @param petLevel 宠物等级
     * @param isFight  是否参战
     * @return
     */
    public Pet addPet(Role role, String petName, short petLevel, boolean isFight) {
        // TODO 拷贝了之前的代码，后续再看怎么优化
        return addPet( role,  petName,  petLevel,  isFight, false);
    }

    public Pet addPet(Role role, String petName, short petLevel, boolean isFight,boolean limit) {
        // TODO 拷贝了之前的代码，后续再看怎么优化
        PetObject petObject = PetDataPool.getPetObject(petName);
        if (petObject != null) {
            Pet pet = addPet(petObject, role, limit);
            if (pet.getLevel() >= 20) {
                roleService.setPetSkill(role, pet);
            }
            pet.setLevel(petLevel);
            loadPet(role, pet);
            RespIconCartoon respIconCartoon = new RespIconCartoon();
            respIconCartoon.setType((short) 2);
            respIconCartoon.setName(pet.getName());
            respIconCartoon.setParam(petObject.getIcon() + "");
            MessagePusher.pushMessage(role, respIconCartoon);

            /**参战时处理逻辑*/
            if (isFight) {
                role.getPetBox().setFightPetId(pet.getId());
                role.save();

                RespSetCurrentPet respSetCurrentPet = new RespSetCurrentPet();
                respSetCurrentPet.setPetId(role.getPetBox().getFightPetId());
                respSetCurrentPet.setStatus((byte) 1);
                MessagePusher.pushMessage(role, respSetCurrentPet);
            }

            if (pet.getLevel() >= 20) {
                roleService.setPetSkill(role, pet);
            }
            return pet;
        }

        return null;
    }

    /**
     * 宠物栏已满
     *
     * @param role
     * @return
     */
    public boolean isEquippedFull(Role role) {
        return role.getPetBox().equippedPets(role).size() >= 8;
    }
    public boolean isEquippedFull(Role role,String petName) {
        return role.getPetBox().equippedPets(petName).size() >= 8;
    }

    /**
     * 检测宠物栏是否足够
     */
    public boolean checkPetPosEnouth(Role role, int needPosCount) {
        return role.getPetBox().equippedPets(role).size() + needPosCount <= 8;
    }

    /**
     * 取宠物物攻或者法攻最大成长
     */
    private int getPetStdValue(String name, boolean isMag) {
       PetObject petObject = PetDataPool.getPetObject(name);
        if (isMag) {
            return getMaxValue(petObject.getGrowInfo(false, "mag"));
        } else {
            return getMaxValue(petObject.getGrowInfo(false, "phy"));
        }
    }

    public int getRebuildDelta(Pet pet) {
        int rebuildAdd = 0, std = 0;
        if (pet.getPolar() > 0) {
            rebuildAdd = pet.getMagRebuildAdd();
            std = getPetStdValue(pet.getName(), true) - 40;
            return FormulaUtil.getMagRebuildDelta(std, rebuildAdd);
        } else {
            rebuildAdd = pet.getPhyRebuildAdd();
            std = getPetStdValue(pet.getName(), false) - 40;
            return FormulaUtil.getPhyRebuildDelta(std, rebuildAdd);
        }
    }

    /**
     * 获取某宠物的最大强化等级
     */
    public int getMaxDevelopLevel(Pet pet) {
        int rebuildAdd = 0;
        if (pet.getPolar() > 0) {
            rebuildAdd = pet.getMagRebuildAdd();
        } else {
            rebuildAdd = pet.getPhyRebuildAdd();
        }
        int max_level = 0;
        if (pet.getPolar() > 0) {
            max_level = pet.getMagRebuildLevel();
        } else {
            max_level = pet.getPhyRebuildLevel();
        }
        int attr = 0;
        int delta = 0;
        if (pet.getPolar() > 0) {
            int mag_std = getPetStdValue(pet.getName(), true) - 40;
            do {
                delta = FormulaUtil.getMagRebuildDelta(mag_std, rebuildAdd + attr);
                if (delta > 0) {
                    max_level = max_level + 1;
                    attr = attr + delta;
                }
            }
            while (delta > 0);
        } else {
            int phy_std = getPetStdValue(pet.getName(), false) - 40;

            do {
                delta = FormulaUtil.getPhyRebuildDelta(phy_std, rebuildAdd + attr);
                if (delta > 0) {
                    max_level = max_level + 1;
                    attr = attr + delta;
                }
            } while (delta > 0);
        }

        if (max_level > 12) {
            max_level = 12;
        }
        return max_level;
    }

    /**
     * 发送野生宠物列表
     */
    public void sendPetShop(Role role) {
        RespPetShop respPetShop = new RespPetShop();
        ArrayList<PetShop> arrayList = new ArrayList<>();
        for (Map.Entry<String, PetShop> entry : ShopDataPool.getName2PetShop().entrySet()) {
            arrayList.add(entry.getValue());
        }
        respPetShop.setType((byte) 1);
        respPetShop.setList(arrayList);
        MessagePusher.pushMessage(role, respPetShop);
    }

    /**
     * 提交宠物
     */
    public void submitPet(Role role, int petId) {
        Byte submitType = (Byte) role.popTempCache(Const.SUBMIT_PET_TYPE);
        if (submitType == null) {
            return;
        }

        Pet pet = role.getPetBox().getPetByPetId(petId);
        switch (submitType) {
            case Const.SUBMIT_PET_TYPE_FEISHENG:
                SpringUtils.getBean(PetFlyTaskHandler.class).confirmChooseFlyPet(role, pet,2);
                break;
            case Const.SUBMIT_PET_TYPE_FEISHENG_GHOST:
                SpringUtils.getBean(PetFlyTaskHandler.class).confirmChooseFlyPet(role, pet,5);
                break;
        }
    }

    /**
     * 返回贵重宠物ID
     */
    public String getValuablePetIdstr(Role role) {
        StringBuilder petIds = new StringBuilder();
        Set<Integer> equippedIds = role.getPetBox().allPets();
        for (Integer petId : equippedIds) {
            Pet pet = getPetById(petId, role);
            if (pet != null && !pet.isInStore()) {
                if (pet.isExpensive()) {
                    petIds.append(petId).append("|");
                }
            }
        }
        String str = petIds.toString();
        if (!Strings.isEmpty(str)) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    public boolean isFullEffect(Pet pet) {
        PetObject petObject =PetDataPool.getPetObject(pet.getName());
        int phy = getMaxValue(petObject.getGrowInfo(false, "phy"));
        int mag = getMaxValue(petObject.getGrowInfo(false, "mag"));
        int life = getMaxValue(petObject.getGrowInfo(false, "life"));
        int mana = getMaxValue(petObject.getGrowInfo(false, "mana"));
        int speed = getMaxValue(petObject.getGrowInfo(false, "speed"));
        if(speed<pet.getSpeedEffect()){
           return false;
        }
        if(phy<pet.getPhyEffect()){
            return false;
        }
        if(mag<pet.getMagEffect()){
            return false;
        }
        if(life<pet.getLifeEffect()){
            return false;
        }
        if(mana<pet.getManaEffect()){
            return false;
        }
        return true;
    }

    /**学习宠物技能*/
    public void learnPetSkill(Role role, Pet pet, short skillId, short addLevel) {
        Skill skill = skillService.getSkillInfo(skillId);
        if (skill == null) {
            return;//没有技能信息
        }

        if (PetDataPool.isInnateSkill(skill.getSkillName())) {
            /**天生技能*/
            /**天生技能需要先通过秘笈书籍学习*/
            RoleSkill petSkill = skillService.getPetSkill(skillId, pet);
            if (petSkill == null) {return ;}

            if (pet.getIntimacy() < Const.LEARN_PET_INNATE_SKILL_INTIMACY) {
                MessagePusher.notify2Player(role, I18nId.PMT_411, Const.LEARN_PET_INNATE_SKILL_INTIMACY);
                return ;
            }

            /**升级技能*/
            if (!checkResource(role, pet, skill, addLevel)) {
                return ;
            }
            substractResource(role, pet, skill, addLevel);

            upgradePetSkill(role, pet, skill, addLevel);
        } else if (PetDataPool.isDevelopSkill(skill.getSkillName())) {
            /**研发技能*/
            if (pet.getIntimacy() < Const.LEARN_PET_DEVELOP_SKILL_INTIMACY) {
                MessagePusher.notify2Player(role, I18nId.PMT_411, Const.LEARN_PET_DEVELOP_SKILL_INTIMACY);
                return ;
            }

            if (!checkResource(role, pet, skill, addLevel)) {
                return ;
            }
            substractResource(role, pet, skill, addLevel);

            if (skillService.getPetSkill(skillId, pet) == null) {
                /**增加技能*/
                addPetSkill(role, pet, skill);
            } else {
                /**升级技能*/
                upgradePetSkill(role, pet, skill, addLevel);
            }
        }
    }

    /**
     * 顿悟技能
     * @param role
     * @param pet
     * @param skillId
     * @param addLevel
     */
    public void dunwuPetSkill(Role role, Pet pet, short skillId, short addLevel,RespForgetPetSkill respForgetPetSkill) {
        Skill skill = skillService.getSkillInfo(skillId);
        if (skill == null) {
            return;//没有技能信息
        }
        /**研发技能*/
        if (pet.getIntimacy() < Const.LEARN_PET_DEVELOP_SKILL_INTIMACY) {
            MessagePusher.notify2Player(role, I18nId.PMT_411, Const.LEARN_PET_DEVELOP_SKILL_INTIMACY);
            return;
        }

        if (skillService.getPetSkill(skillId, pet) == null) {
            /**增加技能*/
            respForgetPetSkill.setA((byte)0);
            addPetSkill(role, pet, skill);
        } else {
            /**升级技能*/
            respForgetPetSkill.setA((byte)1);
            upgradePetSkill(role, pet, skill, addLevel);
        }
    }

    /**添加宠物技能*/
    private void addPetSkill(Role role, Pet pet, Skill skill) {
        RoleSkill roleSkill = new RoleSkill();
        roleSkill.setName(skill.getSkillName());
        roleSkill.setRoleId(pet.getId());
        roleSkill.setType((short) skill.getSkillType());
        roleSkill.setSkillId(skill.getSkillId());
        roleSkill.setSkillJieshu(skill.getJeishu());
        roleSkill.setLevel((short) 1);
        roleSkill.setMana(30);
        roleSkill.setTargetCount((short) skill.getMaxTarget());
        SpringUtils.getSkillService().petLearn(roleSkill, role, pet);
        SpringUtils.getPetService().loadPet(role, pet);
    }

    /**升级宠物技能*/
    private void upgradePetSkill(Role role, Pet pet, Skill skill, short upLevel) {
        SkillService skillService = SpringUtils.getSkillService();
        RoleSkill petSkill = skillService.getPetSkill(skill.getSkillId(), pet);

        short newLevel = (short) (petSkill.getLevel() + upLevel);

        /**增加等级*/
        petSkill.setLevel(newLevel);
        role.save();

        SpringUtils.getPetService().loadPet(role, pet);
    }

    /**检测资源*/
    private boolean checkResource(Role role, Pet pet, Skill skill, short upLevel) {
        int curSkillLevel = 0;
        RoleSkill petSkill = skillService.getPetSkill(skill.getSkillId(), pet);
        if (petSkill != null) {
            curSkillLevel = petSkill.getLevel();
        }

        /**帮派技能等级研发不足时，不能升级*/
        short newLevel = (short) (curSkillLevel + upLevel);
        short skillLevel = SpringUtils.getPartyService().getSkillLevel(role, skill.getSkillId());
        if (newLevel > skillLevel) {
            MessagePusher.notify2Player(role, I18nId.PMT_380, skill.getSkillName(), newLevel);
            return false;
        }

        /**判断金钱是否足够*/
        int money = role.getMoney();
        int costMoney = getCostCashPetUpgradeSkill((short) curSkillLevel, upLevel);
        if (money < costMoney) {
            MessagePusher.notify2Player(role, I18nId.PMT_401);
            return false;
        }

        /**判断帮贡是否足够*/
        int contrib = SpringUtils.getPartyService().getContrib(role);
        int costContrib = getCostContribPetUpgradeSkill((short) curSkillLevel, upLevel);
        if (contrib < costContrib) {
            MessagePusher.notify2Player(role, I18nId.PMT_409);
            return false;
        }

        return true;
    }

    /**扣除资源*/
    private void substractResource(Role role, Pet pet, Skill skill, short upLevel) {
        RoleSkill petSkill = skillService.getPetSkill(skill.getSkillId(), pet);
        int curSkillLevel = 0;
        if (petSkill != null) {
            curSkillLevel = petSkill.getLevel();
        }
        int costMoney = getCostCashPetUpgradeSkill((short) curSkillLevel, upLevel);
        int costContrib = getCostContribPetUpgradeSkill((short) curSkillLevel, upLevel);

        /**扣除金钱和帮贡*/
        SpringUtils.getRoleService().subtractMoney(role, costMoney, Reason.PET_UPGRADE_SKILL);
        SpringUtils.getPartyService().substractContrib(role, costContrib);
    }

    /**获取宠物研发技能升级所消耗的资金*/
    public int getCostCashPetUpgradeSkill(short curLevel, short addLevel) {
        int needCash = 0;
        short toLevel = (short) (curLevel + addLevel);

        for (int i=curLevel; i<= toLevel -1; i++) {
            needCash = needCash + (15 * (i) * (i) + 240 * (i) + 1600);
        }

        return (int) Math.floor(needCash);
    }

    /**获取宠物研发技能所消耗的帮贡*/
    public int getCostContribPetUpgradeSkill(short curLevel, short addLevel) {
        int needContrib = 0;
        short toLevel = (short) (curLevel + addLevel);

        for (int i=curLevel; i<=toLevel - 1; i++) {
            needContrib = (int) (needContrib + Math.ceil(0.02 * i * i + 2 * i));
        }

        return (int) Math.floor(needContrib);
    }

    public boolean isEquippedGhostFull(Role role) {
        return role.getPetBox().yingjian().size() >= 8;
    }
    @Autowired
    private NewNpcService newNpcService;


    public void npcButton(Role role, String msg, NPC npc) {
        if(StringUtils.isBlank(msg)){
            return;
        }

    }
}
